package com.mtung.concurrent.thread;

/**
 * @author zhenguo.yao
 * @date 2020/12/23
 */
public class Thread05 extends Thread {

    static class User {
        public String name;
        public Integer age;
        public boolean execWrite = true;
    }

    static class ReadThread extends Thread {

        User user;

        ReadThread(User user) {
            this.user = user;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    if (!user.execWrite) {
                        System.out.println(Thread.currentThread().getName() + "," + user.name + "," + user.age);
                        try {
                            user.notify();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        user.execWrite = true;
                    }
                }
            }
        }
    }

    static class WriteThread extends Thread {
        User user;

        WriteThread(User user) {
            this.user = user;
        }

        @Override
        public void run() {
            int count = 0;
            while (true) {
                synchronized (user) {
                    if (user.execWrite) {
                        if (count == 0) {
                            user.name = "小明";
                            user.age = 20;
                        } else {
                            user.name = "老明";
                            user.age = 50;
                        }
                        System.out.println(Thread.currentThread().getName() + "," + user.name + "," + user.age);
                        count = (count + 1) % 2;
                        user.execWrite = false;
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        User user = new User();
        WriteThread writeThread = new WriteThread(user);
        writeThread.setName("writeThread");
        ReadThread readThread = new ReadThread(user);
        readThread.setName("readThread");
        writeThread.start();
        readThread.start();
    }


}
